package com.daidai.testservice

import android.content.*
import android.os.Bundle
import android.os.IBinder
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.lang.StringBuilder
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    var receiver: PushReceiver? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        findViewById<Button>(R.id.btn).setOnClickListener {
            // 启动一个服务
            val intent = Intent()
            intent.component = ComponentName(
                "com.sihai.tiantianjianzou",
                "com.helloandroid.services.TestServer"
            )
            intent.action = "aa.bb.cc.dd.ee"
            startService(intent)
            bindService(intent, object : ServiceConnection {
                override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                    MyLog.info("============= 绑定成功")
                }

                override fun onServiceDisconnected(name: ComponentName?) {
                    MyLog.info("============= 绑定断开")
                }
            }, Context.BIND_AUTO_CREATE)
            MyLog.info(" 调用了启动服务")
        }

        findViewById<Button>(R.id.btn2).setOnClickListener {
            val intent = Intent()
            intent.component = ComponentName(
                "com.sihai.tiantianjianzou",
                "com.helloandroid.services.TestRemoteActivity"
            )
            startActivity(intent)
            MyLog.info(" 调用了启动Activity")
        }


        // 模拟推送
        findViewById<Button>(R.id.btn3).setOnClickListener {
            val intent = Intent()
            intent.action = "com.moni.push"
            sendBroadcast(intent)
        }

        //
        receiver = PushReceiver()
        registerReceiver(receiver, IntentFilter("com.moni.push"))

        // 弹
        XXPermissions.with(this)
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .request { _, all ->
                if (all) {
                }
            }
    }

    override fun onDestroy() {
        receiver?.let {
            unregisterReceiver(it)
        }
        super.onDestroy()
    }

    fun startAct() {
        val intent = Intent()
        intent.component = ComponentName(
            "com.sihai.tiantianjianzou",
            "com.helloandroid.services.TestRemoteActivity"
        )
        startActivity(intent)
        MyLog.info(" 调用了启动Activity")
    }

    inner class PushReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            MyLog.info("收到广播!")
            if (intent.action == "com.moni.push") {

                val pendingResult: PendingResult = goAsync()
                thread {
                    startAm()
                }

//                thread {
//                    // 每3s 发送一个
////                    while (true){
////                        MyLog.info("=========去启动 走路里面的服务!!!")
////                        startAct()
////                        Thread.sleep(3000)
////                    }
//
//
//
//                }
            }
        }
    }

    fun startAm() {
        MyLog.info("==== 看看能否启动 activity")

          shellExec()

////        val pb = ProcessBuilder("am start -n com.sihai.tiantianjianzou/com.helloandroid.services.TestRemoteActivity")
//        val pb = ProcessBuilder("ls")
//
//        //设置环境变量，初始值是当前进程环境的一个副本System.getenv()
////        val env = pb.environment()
////        env["VAR1"] = "myValue"
////        env.remove("OTHERVAR")
////        env["VAR2"] = env["VAR1"].toString() + "suffix"
//
//        pb.directory(File("/"))
//        val process = pb.start()
//        process.waitFor()
    }

    fun shellExec() {
        val cmdLst = partitionCommandLine("am")
        MyLog.info("cmdLst:${cmdLstToStr(cmdLst!!)}")
        cmdLst?.let{
            run_command(it,File("/"))
        }


//        val cmdList = ArrayList<String>()
//        cmdList.add("cd /sdcard")
//        val pb = ProcessBuilder(cmdList)
//        pb.redirectErrorStream(true)
//        val process = pb.start()
//        process.waitFor()
//        val sb = StringBuilder()
//        val reader = BufferedReader(InputStreamReader(process.inputStream))
//        var str = reader.readLine()
//        while (str != null) {
//            sb.append(str)
//            str = reader.readLine()
//        }
//        reader.close()
//        MyLog.info("结果为:${sb.toString()}")


        /* val mRuntime = Runtime.getRuntime()
         try {
             //Process中封装了返回的结果和执行错误的结果
             val mProcess = mRuntime.exec("ls")
             val mReader = BufferedReader(InputStreamReader(mProcess.inputStream))
             val mRespBuff = StringBuffer()
             val buff = CharArray(1024)
             var ch = 0
             while (mReader.read(buff).also { ch = it } != -1) {
                 mRespBuff.append(buff, 0, ch)
             }
             mReader.close()
             MyLog.info(mRespBuff.toString())
         } catch (e: IOException) {
             // TODO Auto-generated catch block
             e.printStackTrace()
         }*/
    }

    fun run_command(command: Array<String?>, work_path: File?): Boolean {
        val result_list: MutableList<String> = ArrayList()
        val hiveProcessBuilder = ProcessBuilder(*command)
        hiveProcessBuilder.directory(work_path)
        hiveProcessBuilder.redirectErrorStream(true)
        val hiveProcess = hiveProcessBuilder.start()
        val std_input = BufferedReader(InputStreamReader(hiveProcess.inputStream, "UTF-8"))
        val std_error = BufferedReader(InputStreamReader(hiveProcess.errorStream, "UTF-8"))
        var line: String? = null
        line = std_input.readLine()
        while (line != null) {
            result_list.add(line)
            line = std_input.readLine()
        }
        line = std_error.readLine()
        while (line != null) {
            MyLog.info(line)
            line = std_error.readLine()
        }
        hiveProcess.waitFor()
        if (hiveProcess.exitValue() != 0) {
            MyLog.info("failed to execute:${cmdLstToStr(command)}")
            return false
        }
        MyLog.info("execute success:${cmdLstToStr(command)}")
        std_input.close()
        std_error.close()
        MyLog.info("result_list:${result_list}")
        return true
    }

    fun partitionCommandLine(command: String): Array<String?>? {
        val commands: ArrayList<String> = ArrayList()
        var index = 0
        var buffer = StringBuffer(command.length)
        var isApos = false
        var isQuote = false
        while (index < command.length) {
            val c = command[index]
            when (c) {
                ' ' -> if (!isQuote && !isApos) {
                    val arg = buffer.toString()
                    buffer = StringBuffer(command.length - index)
                    if (arg.length > 0) {
                        commands.add(arg)
                    }
                } else {
                    buffer.append(c)
                }
                '\'' -> if (!isQuote) {
                    isApos = !isApos
                } else {
                    buffer.append(c)
                }
                '"' -> if (!isApos) {
                    isQuote = !isQuote
                } else {
                    buffer.append(c)
                }
                else -> buffer.append(c)
            }
            index++
        }
        if (buffer.length > 0) {
            val arg = buffer.toString()
            commands.add(arg)
        }
        return commands.toArray(arrayOfNulls(commands.size))
    }

    fun cmdLstToStr(lst:Array<String?>):String{
        val sb = StringBuilder()
        lst.forEach { sb.append(it) }
        return sb.toString()
    }
}